package com.hd.aop0410.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.lang.reflect.Method;

@Component
@Aspect
public class CalculateTimeAspect {
    @Around("@annotation(com.hd.aop0410.aop.CalculateTime)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();//让目标方法继续执行
        long end = System.currentTimeMillis();
        String loginfo = "自定义注解time user ->" + (end - start)+"ms";
        //System.out.println(loginfo);
        //把日志信.息打印到@CalculateTime注解配置的文件中

        //通过spring框架传入的pjp对象，可以获取到目标方法对象
        MethodSignature signature=(MethodSignature)pjp.getSignature();
        //获取到目标方法对应的反射Method对象
        Method method = signature.getMethod();
        //获取目标方法上面的注解@CalculateTime
        CalculateTime annotation = method.getAnnotation(CalculateTime.class);
        //获取注解对象上配置的logfilepath属性
        //获取注解对象上配置的overtime属性
        String logfilepath = annotation.logfilepath();
        long overtime = annotation.overtime();
        if (logfilepath!=null&&!logfilepath.equals("")&&(end - start)>overtime){
            //添加方法战行的衣长行丛到文本文
            BufferedWriter bw = new BufferedWriter(new FileWriter(logfilepath, true));
            bw.write(method+"::"+loginfo);
            bw.newLine();
            bw.close();
        }
        return result;
    }
}
